/**
 * 数据列表型模块
 */

import $ from '@/common'
export default {
  name: 'list',
  state: {
    listData: [],
    listModel: {},
    selectList: {},
    bill_code: null,
    serialSort: false
  },
  getters: {
    selectedData(state) {
      var list = {}
      for (let i in state.selectList) {
        if (state.selectList[i]) {
          list[i] = state.listData[i]
        }
      }
      return list
    },
    selectedCount(state) {
      var count = 0
      for (let i in state.selectList) {
        if (state.selectList[i]) {
          count++
        }
      }
      return count
    }
  },
  actions: {
    fetch() {},
    update() {},
    rowUp({ commit }, index) {
      commit('setRowUp', index)
    },
    rowDown({ commit }, index) {
      commit('setRowDown', index)
    }
  },
  mutations: {
    setData(state, data) {
      if (state.serialSort) {
        data.sort((a, b) => {
          return a.serial - b.serial
        })
      }
      $.set(state, 'listData', data || [])
    },
    setSelectList(state, data) {
      $.set(state, 'selectList', data || [])
    },
    appendData(state, data) {
      data.forEach((row) => {
        state.listData.push(row)
      })
    },
    clearData(state) {
      $.set(state, 'listData', [])
    },
    addRow(state, row) {
      state.listData.push(row)
    },
    addEmptyRow(state, row) {
      state.listData.push({})
    },
    removeRow(state, index) {
      state.listData.splice(index, 1)
    },
    editRow(state, { index, data }) {
      $.set(state.listData, index, data)
    },
    setRowField(state, { index, code, value }) {
      if (!state.listData[index]) {
        $.set(state.listData, index, {})
      }
      $.set(state.listData[index], code, value)
    },
    setRowUp(state, index) {
      // serial 改变？
      if (state.listData[index] && (index > 0)) {
        var temp = state.listData[index - 1]
        $.set(state.listData, index - 1, state.listData[index])
        $.set(state.listData, index, temp)
      }
    },
    setRowDown(state, index) {
      if (state.listData[index] && (index < state.listData.length - 1)) {
        var temp = state.listData[index + 1]
        $.set(state.listData, index + 1, state.listData[index])
        $.set(state.listData, index, temp)
      }
    },
    setSerialSort(state, v) {
      state.serialSort = v
    },
    setListModel(state, model) {
      $.set(state, 'listModel', model)
      state.bill_code = model.bill_code
    },
    setActions(state, data) {
      $.set(state.listModel, 'actions', data)
    },
    sortData(state, data) {},
    filter(state, data) {}
  }
}
